#!/usr/bin/python3


from flask import Flask, request, jsonify
import json


app = Flask(__name__)

# from 表单版本
@app.route('/save', methods=['POST'])
def save_data():
    age = request.form.get('age')
    name = request.form.get('name')

    with open('/tmp/flask.txt', 'a+') as file:
        file.write(f'Name: {name}\nAge: {age}\n')

    return 'Data saved successfully!'

# ajax版本
@app.route('/api/data', methods=['POST'])
def process_ajax_request():
    # 从 AJAX 请求中获取数据
    data = request.json

    # 处理数据
    name = data.get('name')
    age = data.get('age')

    # 执行其他操作，例如保存到数据库等

    # 构建响应数据
    response_data = {
        'status': 'success',
        'message': f'Hello, {name}! Your age is {age}.'
    }

    rdata = {
        'age': '25',
        'name': 'John'
    }
    print(rdata)
    print(response_data)
    # 返回 JSON 格式的响应
    return jsonify(response_data)
    # return jsonify;

if __name__ == '__main__':
    app.run(host="0.0.0.0")

